package com.estore.network;

import com.estore.Product;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.List;
import java.util.Scanner;

public class EStoreClient {
    private static final String SERVER_HOST = "localhost";
    private static final int SERVER_PORT = 8888;

    public static void main(String[] args) {
        EStoreClient client = new EStoreClient();
        client.start();
    }

    public void start() {
        Scanner scanner = new Scanner(System.in);

        while (true) {
            System.out.println("\n=== 电子商城客户端 ===");
            System.out.println("1. 浏览所有商品");
            System.out.println("2. 测试服务器连接");
            System.out.println("3. 退出");
            System.out.print("请选择操作: ");

            String choice = scanner.nextLine();

            switch (choice) {
                case "1":
                    browseProducts();
                    break;
                case "2":
                    testServerConnection();
                    break;
                case "3":
                    System.out.println("谢谢使用，再见！");
                    scanner.close();
                    return;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }

    private void browseProducts() {
        Socket socket = null;
        ObjectOutputStream outputStream = null;
        ObjectInputStream inputStream = null;

        try {
            // 连接服务器
            socket = new Socket(SERVER_HOST, SERVER_PORT);

            // 创建输入输出流（注意顺序）
            outputStream = new ObjectOutputStream(socket.getOutputStream());
            inputStream = new ObjectInputStream(socket.getInputStream());

            // 发送请求
            outputStream.writeObject("GET_ALL_PRODUCTS");
            outputStream.flush();

            // 接收响应
            Object response = inputStream.readObject();

            if (response instanceof List) {
                @SuppressWarnings("unchecked")
                List<Product> products = (List<Product>) response;

                System.out.println("\n=== 商品列表 ===");
                if (products.isEmpty()) {
                    System.out.println("暂无商品");
                } else {
                    for (int i = 0; i < products.size(); i++) {
                        Product product = products.get(i);
                        System.out.printf("%d. %s - 价格: ¥%.2f - 库存: %d%n",
                                i + 1, product.getName(), product.getPrice(), product.getStock());
                    }
                }
            } else {
                System.out.println("服务器返回了意外的响应: " + response);
            }

        } catch (IOException e) {
            System.err.println("连接服务器失败: " + e.getMessage());
            System.out.println("请确保服务器已启动！");
        } catch (ClassNotFoundException e) {
            System.err.println("解析服务器响应失败: " + e.getMessage());
        } finally {
            // 关闭资源
            try {
                if (inputStream != null) inputStream.close();
                if (outputStream != null) outputStream.close();
                if (socket != null) socket.close();
            } catch (IOException e) {
                System.err.println("关闭连接时出错: " + e.getMessage());
            }
        }
    }

    private void testServerConnection() {
        Socket socket = null;
        ObjectOutputStream outputStream = null;
        ObjectInputStream inputStream = null;

        try {
            socket = new Socket(SERVER_HOST, SERVER_PORT);
            outputStream = new ObjectOutputStream(socket.getOutputStream());
            inputStream = new ObjectInputStream(socket.getInputStream());

            outputStream.writeObject("GET_SERVER_INFO");
            outputStream.flush();

            Object response = inputStream.readObject();
            System.out.println("服务器响应: " + response);
            System.out.println("连接测试成功！");

        } catch (IOException e) {
            System.err.println("连接测试失败: " + e.getMessage());
        } catch (ClassNotFoundException e) {
            System.err.println("解析服务器响应失败: " + e.getMessage());
        } finally {
            try {
                if (inputStream != null) inputStream.close();
                if (outputStream != null) outputStream.close();
                if (socket != null) socket.close();
            } catch (IOException e) {
                System.err.println("关闭连接时出错: " + e.getMessage());
            }
        }
    }
}
